/**
 * Created by hzc
 */
var LOAD_DATA_COUNT = 0;
var submitFn = true;//防止重复提交
(function(doc, win) {

    //var soucherCHangeFlag = false;//是否需要重新获取活动预期效果

    // sui 页面就绪时间
    $(doc).on("pageInit", "#smCreateNewPage", function(e, pageId, $page,isBack) {
        var controller = new ActivityCreateNewMemberSmController();
        ActivityPreloadData.loadDataTimer({
            "func0" : function() {
                ActivityPreloadData.createPrerequisite();
            },
            "func1" : function(){
                ActivityPreloadData.checkSupplierIsSignedKouBeiKe();
            },
            "func2" : function(){
                ActivityPreloadData.getKouBeiKeConfigInfo();
            },
            "callBackEvent" : function() {
                if(isBack){
                    // 其他设置页返回，需要保存其他设置页的参数信息
                    var paramObj = CommonUtil.takeOutParamObject();
                    $.extend(createActivityPublicParam.otherSetting,paramObj);
                    return;
                }else{
                    // 从首页点击来,保存默认券信息
                    var defaultParam = CommonUtil.takeOutParamObject();

                    defaultParam.activityStartTime = DateUtil.getDateFormat(new Date());
                    defaultParam.activityEndTime = DateUtil.getDateFormat(DateUtil.addDays(new Date(),30));
             
                    createActivityPublicParam.activityType = defaultParam.activityType;
                    createActivityPublicParam.activityStartTime = defaultParam.activityStartTime;
                    createActivityPublicParam.activityEndTime = defaultParam.activityEndTime;

                    $.extend(createActivityPublicParam.defaultParam,defaultParam);
                    
                    //生成默认其他页面参数        
                    generateDefaultOtherSetting();
                    controller.initFirstPage(defaultParam);
                }
            }
        });
    });


    /**
     * 提交活动;
     */
    $(doc).on("click","#smCreateNewPage .submit",function(){
        if(submitFn == true){
            submitFn = false;
            function MyActivity() {
                SubmitActivityData.call(this);
            }
            MyActivity.prototype = Object.create(SubmitActivityData.prototype);
            MyActivity.prototype.checkParams = function () { 
               var actEndDate = $("#smCreateNewPage .activityEndTime").val();
               if(actEndDate == ""){
                   DialogUtil.dialogWarn("请选择活动结束日期!");
                   return false;
               }
                              
            
               return true;    
            };
            MyActivity.prototype.saveData = function () {
                //获取渠道信息
                ActivityPreloadData.initActivityCheckedChannel("smCreateNewPage");
                //createNewController.saveActivityData();         
            };
            MyActivity.prototype.buildSubmitData = function () {
                this.submitData = buildActivitySubmitData(2);
            };   
            var myActivity = new MyActivity();
            myActivity.send();
            
        } 
        
    });


    //自动续期按钮点击事件
    $(doc).on("change", "#smCreateNewPage .autoDelayFlag", function() {
        createActivityPublicParam.autoDelayFlag = $("#smCreateNewPage .autoDelayFlag").attr("checked")?"Y":"N";
    });

    //返回按钮
    $(doc).on("click", "#smCreateNewPage .back", function() {
        
        //清空公共参数createActivityPublicParam
        ActivityPreloadData.clearCreateActivityParam();
        //跳转到首页
        //$.router.back("index.html");
    });
   
   
    
    //其他页面跳转
    $(doc).on("click", "#smCreateNewPage .link-to-otherSetting", function() {
        jumpOtherSettingPage();
    });

    //恢复默认设置
     $(doc).on("click", "#smCreateNewPage .default", function() {
        //获取默认设置
        var defaultParam = createActivityPublicParam.defaultParam;
        var otherSetting = createActivityPublicParam.otherSetting;
        otherSetting.voucherWorthValue = defaultParam.voucherWorthValue;
        otherSetting.voucherMinConsume = defaultParam.voucherMinConsume;
        otherSetting.voucherMinCost = defaultParam.voucherMinCost;
        otherSetting.voucherRelativeTime = defaultParam.voucherRelativeTime;

        /**copy默认券设置
        **/
        var newPromoTools = $.extend(true,[],defaultParam.promoTools);
        otherSetting.promoTools = newPromoTools;
        
        //口碑客
        if(ACTIVITY_TYPE.NEW_MEMBER.val==createActivityPublicParam.activityType){
            var kbk = $("#smCreateNewPage .qudao-item .channel_kbk");
            kbk.removeClass("checked");

            $("#smCreateNewPage label[name='checkSwitch']").find("input").prop("checked",false);

            createActivityPublicParam.percentageClauseRate = "";
            createActivityPublicParam.percentageClauseMax ="";
            createActivityPublicParam.commissionSettingCheck = "0";
            createActivityPublicParam.isOpenKbk = false;

            $("#qudao-kbk .form-wrapper>ul").find("li").each(function(){     
                 if($(this).attr("class")!=null && $(this).attr("class").indexOf("ischange")!=-1){
                     $(this).addClass("disabled");   
                     $(this).find("div").find("input").attr("readonly","readonly");
                 }
            });
            $("#smCreateNewPage span[name='kbk_desc']").text("开启口碑客"); 
            createActivityPublicParam.isOpenKbk = false;

        }
        

        createActivityPublicParam.activityStartTime = defaultParam.activityStartTime;
        createActivityPublicParam.activityEndTime = defaultParam.activityEndTime;

        var controller = new ActivityCreateNewMemberSmController();
        controller.redrawVoucherView(defaultParam);
        //恢复活动时间
        $("#smCreateNewPage .activityStartTime").val(defaultParam.activityStartTime);
        $("#smCreateNewPage .activityEndTime").val(defaultParam.activityEndTime);

        if(ACTIVITY_TYPE.NEW_MEMBER.val==createActivityPublicParam.activityType){
            //获取预期效果数据
            controller.queryExpectEffect(true);

        }else{
            controller.redrawDefaultView(false);
        }
    });



    /**
        券设置弹窗
    **/
    //打开券设置弹窗
    $(doc).on("click", "#smCreateNewPage .quan", function() {
        
        //券设置弹窗
        showPageWindow("smCreateNewPage","df-yhq");

        var voucherWorthValue = $("#smCreateNewPage .dailog-form .voucherWorthValue").val();
         $("#smCreateNewPage .dailog-form .voucherWorthValue").val(createActivityPublicParam.otherSetting.voucherWorthValue);
         $("#smCreateNewPage .dailog-form .voucherMinConsume").val(createActivityPublicParam.otherSetting.voucherMinConsume);
         $("#smCreateNewPage .dailog-form .voucherRelativeTime").val(createActivityPublicParam.otherSetting.voucherRelativeTime);
         //高亮确认按钮
        $("#smCreateNewPage #df-yhq .sure").removeClass("disabled");

    });

    $(doc).on("click", "#smCreateNewPage .dailog-form .cancel,.dailog-form .layer-overlay", function() {
        closeVoucherView();
    });

    //关闭弹窗-公用
    function closeVoucherView(){
        //券设置弹窗
        var df = $("#smCreateNewPage .dailog-form ");
        df.removeClass("layer-visible");
    }


    //券设置弹窗确认按钮状态控制
    $(doc).on("input", "#smCreateNewPage #df-yhq input", function() {
        var reg = new RegExp("^[0-9]+\.{0,1}[0-9]{0,2}$");   
        var inputVal = $(this).val();
        if(inputVal == ""){
            $(this).val("");
        }else{
            if(!reg.test(inputVal)){
                var indexOfPoint =inputVal.indexOf(".");
                if(indexOfPoint != -1){
                    if(inputVal.substring(indexOfPoint+1).length>2){
                        $(this).val(inputVal.substring(0,indexOfPoint+3));
                    }
                } 
            }else{
                if(inputVal.charAt(0)=='0'&& inputVal.charAt(1)!='' && inputVal.charAt(1)!='.'){
                    $(this).val(Number(inputVal));
                }
            }
            
        }
        var voucherWorthValue = $("#smCreateNewPage #df-yhq .voucherWorthValue").val();
        var voucherMinConsume = $("#smCreateNewPage #df-yhq .voucherMinConsume").val();
        var voucherRelativeTime = $("#smCreateNewPage #df-yhq .voucherRelativeTime").val();
        if(CommonUtil.isEmpty(voucherWorthValue)||CommonUtil.isEmpty(voucherMinConsume)||CommonUtil.isEmpty(voucherRelativeTime)){

            //信息不全,按钮置灰不可用
            $("#smCreateNewPage #df-yhq .sure").addClass("disabled");
        }else{
            //确认按钮高亮可用
            $("#smCreateNewPage #df-yhq .sure").removeClass("disabled");
        }
    });

    /**
        渠道-口碑客设置
    **/

    //口碑客分佣弹窗确认按钮状态控制
    $(doc).on("input", "#smCreateNewPage #qudao-kbk input", function() {
        var reg = new RegExp("^[0-9]+\.{0,1}[0-9]{0,2}$");   
        var inputVal = $(this).val();
        if(inputVal == ""){
            $(this).val("");
        }else{
            if(!reg.test(inputVal)){
                var indexOfPoint =inputVal.indexOf(".");
                if(indexOfPoint != -1){
                    if(inputVal.substring(indexOfPoint+1).length>2){
                        $(this).val(inputVal.substring(0,indexOfPoint+3));
                    }
                } 
            }else{
                if(inputVal.charAt(0)=='0'&& inputVal.charAt(1)!='' && inputVal.charAt(1)!='.'){
                    $(this).val(Number(inputVal));
                }
            }
            
        }
        var percentageClauseRate = $("#smCreateNewPage #qudao-kbk .percentageClauseRate").val();
        var clauseLimit = $("#smCreateNewPage div[name='fenyong-deadline']").children("span").text();
        var percentageClauseMax = $("#smCreateNewPage #qudao-kbk .percentageClauseMax").val();
        if(CommonUtil.isEmpty(percentageClauseRate)||(CommonUtil.isEmpty(percentageClauseMax)&&clauseLimit==="限制")){
            //信息不全,按钮置灰不可用
            $("#smCreateNewPage #qudao-kbk .sure").addClass("disabled");
        }else{
            //确认按钮高亮可用
            $("#smCreateNewPage #qudao-kbk .sure").removeClass("disabled");
        }
    });


    /**
     * 确定事件;
     */
    $(doc).on("click", "#smCreateNewPage .dailog-form .sure", function() {
        if($(this).hasClass("disabled")){
            return;
        } 

        var controller = new ActivityCreateNewMemberSmController();
         var name = $(this).attr("name");    
         if(name == "zfb-sure"){
            //渠道-支付宝
            controller.saveZfbData();
            closeVoucherView();
         }else if(name =="kbk-sure"){
            //渠道-分佣
            if(controller.checkKbKData()){
                controller.saveCommissionData();
                closeVoucherView();
            }
         }else if(name =="voucher-sure"){
            //券
            if(controller.checkVoucherData()){
                controller.saveVoucherData();
                closeVoucherView();
            }
         }

    });



    /**
     * 渠道弹窗click事件;
     * 
     */
    $(doc).on("click", "#smCreateNewPage .qudao-item>ul>li", function() {
          var $channelDivClass = $(this).find("div").attr("class");      
          if($channelDivClass=="qd-icon kbk"){
              if(createActivityPublicParam.signedKbk==false){
              common.confirm({
                    btnLeft : "知道了",
                    title : "",
                    content : "若要使用口碑客，请前去口碑商家进行签约，或咨询客服400-696-9619.",
                    callbackLeft : function() {
                        return;
                        } 
                    });
                 
              }else{
                  //口碑客弹起;
                var df2 = $("#smCreateNewPage #qudao-kbk");
                df2.addClass("layer-visible");      

                 var controller = new ActivityCreateNewMemberSmController();
                 controller.initCommissionPageData(); 

              }
        
          }else if($channelDivClass == "qd-icon zfb"){
                 //支付宝弹起;
                 var df2 = $("#smCreateNewPage #qudao-zfb");
                 df2.addClass("layer-visible");

                 var controller = new ActivityCreateNewMemberSmController();
                 controller.initZfbPageData(); 
          }else if($channelDivClass=="qd-icon xp"){
              if($(this).attr("class")=="checked"){
                  $(this).removeClass("checked"); 
              }else{
                  $(this).addClass("checked");
              }          
          }
         
    });


    /**
     * 设置分佣金比率和上限选择事件;
     */
    $(doc).on("click", "#smCreateNewPage div[name='fenyong-deadline']", function() {
    
        if($("#smCreateNewPage .actions-modal-button").size()>0){
            //应该关闭模态窗口(具体怎么关由伟胜提供方法)
            $.closeModal($("#smCreateNewPage .actions-modal"));
        }
        if(createActivityPublicParam.isOpenKbk==false){
            return;
        }
         var _text = $(this).children("span");
         var _self = $(this);
         var buttons1 = [
             {
                 text: '不限制',
                 onClick: function () {
                     _text.text("不限制");
                     _self.siblings("p").hide();
                     createActivityPublicParam.commissionSettingCheck == "0";
                 }
             },
             {
                 text: '限制',
                 onClick: function () {
                     _text.text("限制");
                     _self.siblings("p").show();
                     createActivityPublicParam.commissionSettingCheck == "1";
                     $("#smCreateNewPage .percentageClauseMax").val("");
                    $("#smCreateNewPage #qudao-kbk .sure").addClass("disabled");
                 }
             }
         ];
         var buttons2 = [
             {
                 text: '取消',
             }
         ];
         var groups = [buttons1, buttons2];
         $.actions(groups);
      });


    /**
     * 取消事件;
     */
    $(doc).on("click", "#smCreateNewPage .dailog-form .cancel", function() {
        var controller = new ActivityCreateNewMemberSmController();
         var name = $(this).attr("name");    
         if(name == "kbk-cancel"){
            //渠道-分佣
            if(createActivityPublicParam.isOpenKbk
                &&!$("#smCreateNewPage .qudao-item .channel_kbk").hasClass("checked")){
                
                $("#smCreateNewPage label[name='checkSwitch']").find("input").prop("checked",false);
                //$("#smCreateNewPage label[name='checkSwitch']").trigger("click");
                                
                  $("#qudao-kbk .form-wrapper>ul").find("li").each(function(){     
                     if($(this).attr("class")!=null && $(this).attr("class").indexOf("ischange")!=-1){
                         $(this).addClass("disabled");   
                         $(this).find("div").find("input").attr("readonly","readonly");
                     }
                  });
                  $("#smCreateNewPage span[name='kbk_desc']").text("开启口碑客"); 
                  createActivityPublicParam.isOpenKbk = false;
            }
         }

    });

    /**
    * 是否开启口碑客切换;
    */
    $(doc).on("change", "#smCreateNewPage label[name='checkSwitch'] input", function () {

      var isOpen = $(this).prop("checked");      
      if(isOpen){

        var percentageClauseRate = $("#smCreateNewPage .percentageClauseRate").val();
        $("#qudao-kbk .form-wrapper>ul").find("li").each(function(){  
          if($(this).attr("class")!=null && $(this).attr("class").indexOf("ischange")!=-1){
              $(this).removeClass("disabled");  
              $(this).find("div").find("input").removeAttr("readonly");
          }                   
         }); 
         $("#smCreateNewPage span[name='kbk_desc']").text("关闭口碑客");
         createActivityPublicParam.isOpenKbk = true;
         if(percentageClauseRate==""||
            $("#smCreateNewPage div[name='fenyong-deadline']").find("span").text()=="限制"
            &&$("#smCreateNewPage .percentageClauseMax").val()==""){

         }else{
            
            $("#smCreateNewPage div[name='kbk-sure']").removeClass("disabled");
         }
      }else{
        $("#qudao-kbk .form-wrapper>ul").find("li").each(function(){     
             if($(this).attr("class")!=null && $(this).attr("class").indexOf("ischange")!=-1){
                 $(this).addClass("disabled");   
                 $(this).find("div").find("input").attr("readonly","readonly");
             }
          });
          $("#smCreateNewPage span[name='kbk_desc']").text("开启口碑客"); 
          createActivityPublicParam.isOpenKbk = false;

         //$(this).addClass("disabled");
         //var controller = new ActivityCreateNewMemberSmController();
         //controller.initCommissionPageData(); 
      }
    
    });

    /**
     * 优惠图片选择＋上传事件;
     */
    $(doc).on("click","#smCreateNewPage .discountPic",function(){
        AppUtil.call(AppUtil.APIS.SELECT_PICTURE,
                {compress : {"sizeLimit" : "2","unit" : "M"},
                 crop:{heightRatio:4,widthRatio:3},
                 format:"JPG",
                 maxNum:1
                },
                function(result){
                    if(result.code == 0){
                        if(result.resultObject && result.resultObject instanceof Array){
                            createActivityPublicParam.voucherSloganLocalFilePath = result.resultObject[0];
                            common.loading("图片上传中...");
                            AppUtil.call(AppUtil.APIS.UPLOAD_PICTURE,
                                    {
                                       "file":createActivityPublicParam.voucherSloganLocalFilePath,
                                       "url":App.serverUrl + "app/img/uploadActivityImg.do"
                                    },
                                    function(result){
                                        if(result.code == 0){
                                            if(result.resultObject && result.resultObject != null){
                                                createActivityPublicParam.voucherSloganNewUri = result.resultObject.resultObject.imageUrl;
                                                createActivityPublicParam.voucherSloganNewId = result.resultObject.resultObject.imageId;  

                                                var picElt = "";
                                                if(createActivityPublicParam.voucherSloganLocalFilePath!=""){
                                                    picElt = "<img src='"+createActivityPublicParam.voucherSloganLocalFilePath+"' alt='优惠专属图片'/><i class='zhk-list_rarrow'></i>";        
                                                }else{
                                                    picElt = "非必选项<i class='zhk-list_rarrow'></i>";
                                                }
                                                $("#smCreateNewPage .discountPic").find("a").html(picElt);
                                            }else{
                                                DialogUtil.dialogWarn("未正确返回图片上传结果!");                      
                                            }
                                                        
                                        }else if(result.code == -1){
                                              DialogUtil.dialogWarn(result.msg);                 
                                        } 
                                        common.closeLoading();
                                });
                            
                        
                        }
                                    
                    }else if(result.code == -1){
                          DialogUtil.dialogWarn("选择图片异常!"+result.msg);
                          return;
                    }                 
            });
     
    });


})(document, window);

